package com.wise.service.portal.content.uploadresources;

import com.wise.entities.content.Resource;
import com.wise.entities.content.ResourceGroup;
import com.wise.framework.dao.SqlSelect;
import com.wise.framework.daomodel.DaoPageList;
import com.wise.framework.restful.PageResultList;
import com.wise.framework.validation.Precondition;
import com.wise.model.content.resourcegroup.ResourceGroupType;
import com.wise.summer.v1.portal.content.uploadresources.ListUploadResources;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.summerframework.model.SummerService;
import org.summerframework.model.SummerServiceBean;

import static com.wise.model.content.ContentErrMsgs.Err_100100000004;

@Service
@SummerService
public class ListUploadResourcesService implements SummerServiceBean<ListUploadResources> {
    @Value("${azure.file.url}")
    private String url;

    @Override
    public void sum(ListUploadResources summer) {
        SqlSelect select = SqlSelect.selec("*")
                .fromClassName(Resource.class, "res")
                .left_outer_join("upload_resource_groups gr on res.group_id=gr.id")
                .eq("gr." + ResourceGroup._groupType, ResourceGroupType.FILE.value())
                .eq(Resource._groupId, summer.getGroupId())
                .eq(StringUtils.isNotBlank(summer.getResourceName()), Resource._resourceName, "%" + summer.getResourceName() + "%")
                .eqLang("res." + Resource._lang)
                .order_by(Resource.UPLOAD_TIME + " desc");
        PageResultList<ListUploadResources.Result> list = DaoPageList.s(ListUploadResources.Result.class, select, summer.getStart(), summer.getLimit());
        Precondition.checkNotNull(list, Err_100100000004);
        if (StringUtils.isNotEmpty(url)) {
            for (ListUploadResources.Result result : list.getList()) {
                int index = result.getPath().lastIndexOf("/");
                String fileName = result.getPath().substring(index + 1);
                result.setPath(url + fileName);
            }
        }
        summer.setSummerResult(list);
    }

}
